package com.chidopi.cdf.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.RequestContextUtils;

public class ItemTag extends SimpleTagSupport {
	private static Logger logger = LoggerFactory.getLogger(ItemTag.class);
	private static WebApplicationContext _applicationContext;
	private String itemId;
	
	public void setItemId(String itemId) {
		this.itemId = itemId;
		logger.debug("ItemID is setted as " + itemId);
	}

	private void initApplicationContext(){
		PageContext pageContext = (PageContext) getJspContext();
		_applicationContext = RequestContextUtils.getWebApplicationContext(
				pageContext.getRequest(),
				pageContext.getServletContext()
		);
		logger.debug("initial context OK!!");
	}
	
	@Override
	public void doTag() throws JspException, IOException {
		if (null == _applicationContext) this.initApplicationContext();
		JspWriter out = this.getJspContext().getOut();
		String username = (String) super.getJspContext().getAttribute("username", PageContext.SESSION_SCOPE);
		logger.debug("username=" + username);
		ITagDao dao = (ITagDao) _applicationContext.getBean("tagDao");
		if (dao != null) {
			try {
				String css = dao.getCSS(username, this.itemId);
				if (css != null) {
					out.print(css);
				}
			} catch (Exception e) {
				logger.warn("dao error", e);
			}
		} else {
			logger.debug("ITagDao is null");
		}
		logger.debug("doTag OK!!");
	}

}
